<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2024-08-26 14:57:33
 * @LastEditors: chenhuanhuan 2925102113@qq.com
 * @LastEditTime: 2024-11-14 17:01:09
 * @FilePath: \orderApp\packageOne\pages\personalInfo\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<route lang="json5" type="page">
{
  layout: "default",
  style: {
    navigationStyle: "custom",
    navigationBarTextStyle: "black",
  },
}
</route>

<template>
  <view class="">
    <cu-navbar title="个人信息"></cu-navbar>
    <view class="wrap">
      <cu-card padding="0 31rpx">
        <uv-cell title="头像" :isLink="true" @click="changeAvatar" >
          <template v-slot:value>
            <uv-avatar :src="user.headPortrait" size="77rpx"></uv-avatar>
          </template>
        </uv-cell>
        <uv-cell
          title="昵称"
          :value="user.nickname"
          :isLink="true"
          @click="modifyInfo(1)"
        ></uv-cell>
        <uv-cell title="手机号" :value="user.contact"></uv-cell>
        <uv-cell
          title="密码"
          value="*****"
          :isLink="true"
          @click="modifyInfo(2)"
        ></uv-cell>
        <uv-cell title="匿名评论/评议" :border="false">
          <template v-slot:value>
            <uv-switch
              v-model="user.anonymous"
              :activeValue="1"
              :inactiveValue="0"
              activeColor="#00754A"
              size="22"
              @change="changeAnonymous"
            ></uv-switch>
          </template>
        </uv-cell>
      </cu-card>

      <cu-card margin="38rpx 0" padding="0 31rpx">
        <uv-cell
          title="伙食灶"
          :value="user.foodOven ? user.foodOven.kitchenName : '未知'"
          :isLink="true"
          @click="showAction(1)"
        >
        </uv-cell>
        <uv-cell
          title="菜系偏好"
          :value="user.likeStyle"
          :isLink="true"
          @click="showAction(2)"
        ></uv-cell>
        <uv-cell
          title="口味偏好"
          :value="user.likeTaste"
          :isLink="true"
          @click="showAction(3)"
        ></uv-cell>
        <uv-cell
          title="健康信息"
          :isLink="true"
          :border="false"
          @click="goHealthy"
        ></uv-cell>
      </cu-card>

      <view @click="logoutFn" class="textBtn"> 退出登录 </view>
    </view>
    <ksp-cropper
      mode="fixed"
      :width="200"
      :height="200"
      :maxWidth="1024"
      :maxHeight="1024"
      :url="imgUrl"
      @cancel="oncancel"
      @ok="selectedImage"
    ></ksp-cropper>

    <!-- <uv-modal ref="modal" title="水调歌头" content='不知天上宫阙，今夕是何年' :showCancelButton="true" @confirm="confirm">
			<template v-slot:confirmButton>
				<uv-button
            shape="circle"
            color="#00754A"
            customStyle="margin-top: 44rpx;height:72rpx;width:230rpx"
            @click="loginHandler"
          >
            <span style="font-size: 31rpx">确认</span>
          </uv-button>
			</template>
      <template v-slot:cancelButton>
				<uv-button
            shape="circle"
            color="#00754A"
            customStyle="margin-top: 44rpx;height:72rpx;width:230rpx"
            @click="loginHandler"
          >
            <span style="font-size: 31rpx">取消</span>
          </uv-button>
			</template>
		</uv-modal> -->

    <uv-picker
      ref="selectRef"
      color="#000000"
      activeColor="#00754A"
      confirmColor="#00754A"
      :columns="[curList]"
      keyName="name"
      :title="title"
      round="15rpx"
      @confirm="optionsSelect"
    ></uv-picker>

    <modify ref="nickPop" title="修改昵称" @confirm="saveNick">
      <uv-input
        placeholder="请输入昵称"
        v-model="newNickname"
        maxlength="10"
        inputAlign="center"
        border="bottom"
      ></uv-input>
    </modify>
    <modify ref="psdPop" title="修改密码" @confirm="savePsd">
      <uv-form
        labelPosition="left"
        :model="psdForm"
        :rules="rules"
        ref="formRef"
        labelWidth="70"
      >
        <uv-form-item label="新密码" prop="newPassword1" borderBottom>
          <uv-input
            v-model="psdForm.newPassword1"
            :password="true"
            maxlength="10"
            clearable
            placeholder="请输入新密码"
            border="none"
          >
          </uv-input>
        </uv-form-item>
        <uv-form-item label="确认密码" prop="newPassword2" borderBottom>
          <uv-input
            v-model="psdForm.newPassword2"
            clearable
            :password="true"
            maxlength="10"
            placeholder="请确认密码"
            border="none"
          >
          </uv-input>
        </uv-form-item>
      </uv-form>
    </modify>
  </view>
</template>

<script lang="ts" setup>
//
import modify from "./components/modify.vue";
import { getCurrentInstance } from "vue";
import type { ComponentInternalInstance } from "vue";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { reqSetUserInfo, reqSetAnonymous, reqDelFile ,logout} from "@/service/business/login";
// 请求基地址
const baseURL = import.meta.env.VITE_SERVER_BASEURL;
import { useUserStore } from "@/store";

const { user } = useUserStore().userInfo;

/**
 * 修改头像
 */
const imgUrl = ref("");
const changeAvatar = () => {
  uni.chooseImage({
    count: 1, // 默认9, 设置图片的选择数量
    sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album"], // 可以指定来源是相册还是相机，默认二者都有
    success: (res) => {
      imgUrl.value = res.tempFilePaths[0];
    },
    fail: (error) => {
      console.log("选择图片失败", error);
    },
  });
};

const oncancel = (res) => {
  imgUrl.value = "";
  console.log("点击取消", res);
};

const selectedImage = (ev) => {
  //url设置为空，隐藏控件
  imgUrl.value = "";
  return new Promise((resolve, reject) => {
    uni.showLoading({
      mask: true,
      title: "上传头像中",
    });
    const uploadOptions = {
      url: baseURL + "/commentApp/common/uploadFile",
      filePath: ev.path, //插件返的临时路径
      name: "file",
      formData: {
        user: "test",
      },
    };
    //调用上传接口，将临时路径转换为https开头的图片格式
    uni.uploadFile({
      ...uploadOptions,
      success: async (res) => {
        try {
          const result = JSON.parse(res.data);
          // 上传成功删除之前的头像资源
          new Promise<void>((resolve, reject) => {
            reqDelFile({ fileName: [user.headPortrait] });
          });

          await updateAvatar(result.data); //调用修改接口，实现修改头像
          uni.hideLoading();
          resolve();
        } catch (error) {
          console.error("上传失败", error);
          reject(error);
        }
      },
    });
  });
};

// 设置头像
const updateAvatar = (img) => {
  let params = {
    headPortrait: img,
    userId: user.userId,
  };
  SetUserInfo(params).then((res) => {
    user.headPortrait = img;
  });
};

const newNickname = ref(JSON.parse(JSON.stringify(user.nickname)));
// 修改昵称
const saveNick = () => {
  console.log(newNickname.value, 88);
  if (newNickname.value == "") {
    uni.showToast({
      title: "昵称不能为空",
      icon: "none",
    });
  } else if (newNickname.value.includes("匿名")) {
    uni.showToast({
      title: `'匿名'为非法字符`,
      icon: "none",
    });
  } else {
    SetUserInfo({ nickname: newNickname.value }).then((res) => {
      user.nickname = newNickname.value;
      nickPop.value.close();
    });
  }
};
const psdOrigin = () => ({
  newPassword1: "",
  newPassword2: "",
});
const psdForm = ref(psdOrigin());
const formRef = ref(null);
const rules = {
  oldpassword: {
    type: "string",
    required: true,
    message: "此项必填",
    trigger: ["blur", "change"],
  },
  newPassword1: {
    type: "string",
    required: true,
    message: "此项必填",
    trigger: ["blur", "change"],
  },
  newPassword2: [
    {
      validator: (rule, value, callback) => {
        if (psdForm.value.newPassword1 !== psdForm.value.newPassword2) {
          callback(new Error("密码不一致"));
        } else {
          // 如果校验通过，也要执行callback()回调
          callback();
        }
      },
      trigger: ["change", "blur"],
    },
    {
      type: "string",
      required: true,
      message: "此项必填",
      trigger: ["blur", "change"],
    },
  ],
};
// 修改密码
const savePsd = () => {
  nickPop.value.close();
  formRef.value
    .validate()
    .then((res) => {
      SetUserInfo(psdForm.value).then((res) => {
        psdForm.value = psdOrigin();
        psdPop.value.close();
      });
    })
    .catch((err) => {
      return;
    });
};

// 设置用户信息
const SetUserInfo = (params) => {
  uni.showLoading({
    title: "修改中",
    mask: true,
  });
  return new Promise<void>((resolve, reject) => {
    reqSetUserInfo({
      userId: user.userId,
      ...params,
    }).then((res) => {
      if (res.retCode === 2000) {
        resolve();
        uni.hideLoading();
      }
    });
  });
};

const nickPop = ref(null);
const psdPop = ref(null);
const modifyInfo = (val) => {
  if (val == 1) {
    nickPop.value.open();
  } else if (val == 2) {
    psdPop.value.open();
  }
};

/**
 *
 */
const goHealthy = () => {
  uni.navigateTo({
    url: "/packageTwo/pages/healthyInfo/index",
  });
};

/**
 * 饮食偏好修改
 */
// 获取伙食灶列表
const foodList = ref([]);

// 获取菜系列表
const styleList = ref([]);

// 获取口味列表
const tasteList = ref([]);

const title = ref("");
const curList = ref([]);
const curIdx = ref(0);

watch(
  user,
  (val) => {
    console.log(val, "userinfo");
  },
  { deep: true }
);

watch(
  curIdx,
  (val) => {
    switch (val) {
      case 1:
        title.value = "伙食灶";
        curList.value = foodList?.value || [];
        break;
      case 2:
        title.value = "菜系偏好";
        curList.value = styleList?.value || [];
        break;
      case 3:
        title.value = "口味偏好";
        curList.value = tasteList?.value || [];
        break;
    }
  },
  { immediate: true }
);

// 设置饮食偏好
const optionsSelect = (e) => {
  const { kitchenId, id, name } = e.value[0];
  if (curIdx.value == 1) {
    let params = {
      kitchenId,
    };
    SetUserInfo(params).then((res) => {
      user.foodOven.kitchenName = name;
      user.foodOven.kitchenId = kitchenId;
    });
  } else if (curIdx.value == 2) {
    let params = {
      likeStyle: name,
    };
    SetUserInfo(params).then((res) => {
      user.likeStyle = name;
    });
  } else if (curIdx.value == 3) {
    let params = {
      likeTaste: name,
    };
    SetUserInfo(params).then((res) => {
      user.likeTaste = name;
    });
  }
};

const selectRef = ref(null);
const showAction = (idx) => {
  curIdx.value = idx;
  selectRef.value.open();
  selectRef.value.setIndexs([0], true);
};

/**
 * 匿名评论
 */
const changeAnonymous = (e) => {
  uni.showLoading({
    title: "设置中",
    mask: true,
  });
  reqSetAnonymous({
    anonymous: Number(e),
    userId: user.userId,
  }).then((res) => {
    if (res.retCode == 2000) {
      uni.hideLoading();
    }
  });
};

// 退出登录 
const logoutFn = ()=>{
  uni.showModal({
        content: "确定要退出当前账户吗？",
        success: (e) => {
          if (e.confirm) {
            uni.showLoading({
              title: "账号退出中...",
              mask: true,
            });
            // 如果匿名登录的用户退出的话，不会调用后台退出接口
            if (user.nickname == "匿名用户") {
              useUserStore().clearUserInfo()
              uni.redirectTo({ url: "/pages/login/login" });
              uni.hideLoading();
            } else {
              logout().then((res) => {
                  uni.hideLoading();
                  if (res.retCode == 2000) {
                    useUserStore().clearUserInfo()
                    uni.redirectTo({ url: "/pages/login/login" });
                  }
                })
                .catch(() => {
                  uni.hideLoading();
                });
            }
          }
        },
      });
}

onMounted(() => {
  proxy?.$global.getFoodOven().then((res) => {
    foodList.value = res.map((el) => {
      el.name = el.kitchenName;
      return el;
    });
  });
  proxy?.$global.getTasteAll().then((res) => {
    tasteList.value = res.map((el) => {
      el.name = el.value;
      return el;
    });
  });
  proxy?.$global.getStyleAll().then((res) => {
    styleList.value = res.map((el) => {
      el.name = el.style;
      return el;
    });
  });
});
</script>

<style lang="scss" scoped>

::v-deep .uv-cell__body{
  padding: 23rpx 0 !important;
}
//
.wrap {
  padding: 31rpx;
}

.textBtn{
  margin: 0 auto;
  // width: 123rpx;
height: 46rpx;
font-family: PingFang SC, PingFang SC;
font-weight: 400;
font-size: 31rpx;
color: #00754A;
line-height: 46rpx;
text-align: center;
font-style: normal;
text-transform: none;
}
</style>
